package com.qf.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.constans.ResultCode;
import com.qf.dto.R;
import com.qf.entity.TMenu;
import com.qf.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
杨威
2021/11/4
15:10
*/
@Component
public class BlackAllInterceptor implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MenuMapper menuMapper;
    //前置通知
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //当前访问的地址
        String uri = request.getRequestURI();
        System.out.println("uri = " + uri);
        TMenu menu = menuMapper.findByUrl(uri);
        System.out.println("menu = " + menu);
        Integer status = menu.getStatus();
        System.out.println(111);
        if(status==0){//代表接口关闭 不让任何人访问
            R error = R.setError(ResultCode.INTERFACE_CLOSE, "接口已经关闭不能访问", null);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(error));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
